package com.example.module_park.ui

import android.app.AlertDialog
import android.app.DatePickerDialog
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.lib_common.base.state.Failed
import com.example.lib_common.base.state.Loading
import com.example.lib_common.base.state.Success
import com.example.lib_common.utils.RouterPath
import com.example.module_park.adapter.AttachmentAdapter
import com.example.module_park.databinding.ActivityEnterpriseApplicationBinding
import com.example.module_park.enterprise.EnterpriseApplicationViewModel
import dagger.hilt.android.AndroidEntryPoint
import java.util.Calendar

@AndroidEntryPoint
@Route(path = RouterPath.APPLICATION_UI)
class EnterpriseApplicationActivity : AppCompatActivity() {

    private lateinit var binding: ActivityEnterpriseApplicationBinding
    private val viewModel: EnterpriseApplicationViewModel by viewModels()
    private val calendar = Calendar.getInstance()
    private lateinit var attachmentAdapter: AttachmentAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEnterpriseApplicationBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initViews()
        initListeners()
        initObservers()
    }

    private fun initViews() {
        // 初始化附件适配器
        attachmentAdapter = AttachmentAdapter(
            items = viewModel.attachments.value,
            onAddClick = { openImagePicker() },
            onRemoveClick = { url -> viewModel.removeAttachment(url) }
        )
        binding.rvAttachments.apply {
            layoutManager = GridLayoutManager(this@EnterpriseApplicationActivity, 3)
            adapter = attachmentAdapter
        }

        // 设置日期选择字段只读
        binding.etEntryTime.apply {
            isFocusable = false
            isClickable = true
        }
    }

    private fun initListeners() {
        // 返回按钮
        binding.btnBack.setOnClickListener {
            onBackPressed()
        }

        // 申请记录按钮
        binding.btnRecord.setOnClickListener {
//            startActivity(Intent(this, ApplicationRecordsActivity::class.java))
        }

        // 日期选择
        binding.etEntryTime.setOnClickListener {
            showDatePicker()
        }

        // 表单数据绑定
        binding.etCompanyName.addTextChangedListener { viewModel.companyName.value = it.toString() }
        binding.etContactName.addTextChangedListener { viewModel.contactName.value = it.toString() }
        binding.etPhone.addTextChangedListener { viewModel.phone.value = it.toString() }
        binding.etArea.addTextChangedListener { viewModel.area.value = it.toString() }
        binding.etPersonCount.addTextChangedListener { viewModel.personCount.value = it.toString() }

        // 提交按钮
        binding.btnSubmit.setOnClickListener {

            viewModel.submitApplication()
          
            finish()
        }
    }

    private fun initObservers() {
        lifecycleScope.launchWhenStarted {
            // 观察日期变化并更新UI
            viewModel.entryDate.collect { date ->
                binding.etEntryTime.setText(date)
            }
        }

        lifecycleScope.launchWhenStarted {
            // 观察附件列表变化并更新UI
            viewModel.attachments.collect { attachments ->
                attachmentAdapter.items = attachments
                attachmentAdapter.notifyDataSetChanged()
            }
        }

        lifecycleScope.launchWhenStarted {
            // 观察提交状态
            viewModel.submitState.collect { state ->
                when (state) {
                    Loading -> setLoadingViewVisible(true)
                    Success -> {
                        setLoadingViewVisible(false)
                        showSuccessDialog()
                    }
                    is Failed -> {
                        setLoadingViewVisible(false)
                        showErrorDialog(state.message)
                    }
                    else -> setLoadingViewVisible(false)
                }
            }
        }
    }

    private fun showDatePicker() {
        DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                viewModel.onDateSelected(year, month + 1, dayOfMonth)
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }

    private fun openImagePicker() {
        // 实际项目中会打开图片选择器
        // 这里模拟添加一个附件
        val dummyUrl = "https://example.com/uploads/${System.currentTimeMillis()}.jpg"
        viewModel.addAttachment(dummyUrl)
    }

    private fun setLoadingViewVisible(visible: Boolean) {
        // 使用BaseActivity提供的加载视图
//        setLoadingViewVisible(visible, "提交中...")

    }

    private fun showSuccessDialog() {
        // 提交成功后显示成功对话框
        AlertDialog.Builder(this)
            .setTitle("提交成功")
            .setMessage("您的申请已提交成功。")
            .setPositiveButton("确定") { _, _ ->
                // 重置表单数据
                viewModel.companyName.value = ""
                viewModel.contactName.value = ""
                viewModel.phone.value = ""
                viewModel.entryDate.value = ""
                viewModel.area.value = ""
                viewModel.personCount.value = ""
               viewModel.attachments.value = emptyList()
            }
    }

    private fun showErrorDialog(message: String) {
        // 显示错误信息对话框
        AlertDialog.Builder(this)
            .setTitle("提交失败")
            .setMessage(message)
            .setPositiveButton("确定") { _, _ ->
                // 重置表单数据
                viewModel.companyName.value = ""
                viewModel.contactName.value = ""
                viewModel.phone.value = ""
                viewModel.entryDate.value = ""
                viewModel.area.value = ""
                viewModel.personCount.value = ""
                viewModel.attachments.value = emptyList()
            }
    }
}